<template>
  <Form ref="loginForm" :model="form" :rules="rules" @keydown.enter.native="handleSubmit">
    <FormItem prop="phone">
      <Input v-model="form.phone" placeholder="请输入手机号">
        <span slot="prepend">
          <Icon :size="16" type="ios-person"></Icon>
        </span>
      </Input>
    </FormItem>
    <FormItem prop="sms_code">
      <Row>
        <Col span="16">
          <Input v-model="form.sms_code" placeholder="请输入验证码">
            <span slot="prepend">
              <Icon :size="14" type="md-lock"></Icon>
            </span>
          </Input>
        </Col>
        <Col span="8">
          <Button :disabled="send_sms_btn.disabled" @click="sendSms" type="default" v-text="send_sms_btn.show_text"></Button>
        </Col>
      </Row>
    </FormItem>
    <FormItem>
      <Button @click="handleSubmit" type="primary" long>登录</Button>
    </FormItem>
  </Form>
</template>
<script>
import {
  sendSMS
} from '@/graphql/mutation/auth'

export default {
  name: 'LoginForm',
  props: {
    phoneRules: {
      type: Array,
      default: () => {
        return [
          { type: 'string', required: true, message: '手机号不能为空,仅能为11位数字', len: 11, pattern: /^[0-9]+$/, trigger: 'blur' }
        ]
      }
    },
    smsCodeRules: {
      type: Array,
      default: () => {
        return [
          { required: true, message: '验证码不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  data () {
    return {
      form: {
        phone: '',
        sms_code: ''
      },
      send_sms_btn: {
        disabled: false,
        default_text: '发送验证码',
        show_text: '发送验证码'
      }
    }
  },
  computed: {
    rules () {
      return {
        phone: this.phoneRules,
        sms_code: this.smsCodeRules
      }
    }
  },
  methods: {
    sendSms () {
      this.send_sms_btn.disabled = true
      sendSMS({
        input: {
          phone: this.form.phone
        }
      }).then((res) => {
        let time = 120
        // 发送验证码
        const timer = setInterval(() => {
          this.send_sms_btn.show_text = `${time}秒后重试`
          if (time < 0) {
            this.send_sms_btn.show_text = this.send_sms_btn.default_text
            this.send_sms_btn.disabled = false
            clearInterval(timer)
          }
          time--
        }, 1000)
      }).catch(() => {
        this.send_sms_btn.show_text = this.send_sms_btn.default_text
        this.send_sms_btn.disabled = false
      })
    },
    handleSubmit () {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          const { phone, sms_code } = this.form
          this.$emit('on-success-valid', {
            phone,
            sms_code
          })
        }
      })
    }
  }
}
</script>
